package com.google.gwt.sample.dynatablerf.server.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TimeoutFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws ServletException, IOException {
		if ((request instanceof HttpServletRequest)
				&& (response instanceof HttpServletResponse)) {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			if (!isValidSession(httpServletRequest)) {
				throw new ServletException("TimeOutException");
			}
			filterChain.doFilter(request, response);
		}
	}

	private boolean isValidSession(HttpServletRequest httpServletRequest) {
		return (httpServletRequest.getRequestedSessionId() != null)
				&& httpServletRequest.isRequestedSessionIdValid();
	}
}
